package com.sdry.web.controller.permission;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.sdry.entity.permission.UpmsRole;
import com.sdry.entity.permission.UpmsStaff;
import com.sdry.entity.permission.UpmsStaffRole;
import com.sdry.service.permission.UpmsRoleService;
import com.sdry.service.permission.UpmsStaffRoleService;
import com.sdry.service.permission.UpmsStaffService;
import com.sdry.utils.DateJsonValueProcessor;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.MD5;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.StringUtil;

/**
*
* @ClassName:UpmsStaffRoleController
* @Description:员工+角色
* @Author tdd
* @Date Mon Jul 30 15:24:43 CST 2018
* @version 1.0
*/
@Controller
@RequestMapping("/upmsStaffRole")
public class StaffRoleController{
   /**注入员工+角色Server*/
   @Resource UpmsStaffRoleService  upmsStaffRoleService;
   /**注入员工Server*/
   @Resource UpmsStaffService  upmsStaffService;
   /**注入角色Server*/
   @Resource UpmsRoleService  upmsRoleService;
   /**
    * 条件分页查询
    * @param upmsStaffRole 员工+角色实体类
    * @param response
    * @return
    * @throws Exception
    */
   @RequestMapping("/list")
   public String list(UpmsStaffRole upmsStaffRole,HttpServletResponse response) throws Exception{
   	/*
   	* 条件分页查询内容
   	*/
   	List<UpmsStaffRole> list = upmsStaffRoleService.findPageByMution(upmsStaffRole);
   	/*
   	* 条件查询总条数
   	*/
   	Integer total = upmsStaffRoleService.selectCountByMution(upmsStaffRole);

   	/*
   	* 转为json数据传至页面
   	*/
   	JsonConfig jsonConfig = new JsonConfig();
   	jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
   	//创建result
   	JSONObject result = new JSONObject();
   	//转json数据
   	JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
   	//添加入result
   	result.put("rows", jsonArray);
   	result.put("total", total);
   	//发送result
   	ResponseUtil.write(response, result);
   	return null;
   }
   /**
    * 添加员工+角色
    * @param upmsStaffRole 员工+角色实体类
    * @param session
    * @param response
    * @return
    * @throws Exception
   */
   @RequestMapping("/add")
   public void add(String pass,UpmsStaffRole upmsStaffRole,HttpSession session, HttpServletResponse response) throws Exception{
       
	   /*
        * 添加返回id
       */
       Long id = upmsStaffRoleService.insert(upmsStaffRole);
       if (null != id) {
    	   UpmsStaff param = upmsStaffService.queryById(upmsStaffRole.getStaffId());
    	   if (StringUtil.isNotEmpty(pass)) {
    		   param.setPass(MD5.md5Encode(pass));
    	   }else{
    		   param.setPass(MD5.md5Encode("123"));
    	   }
    	   upmsStaffService.update(param);
           response.getWriter().print("1");
       }else{
           response.getWriter().print("0");
       }
   }
   /**
    * 多删除
    * @param ids 员工+角色id累加字符串
    * @param session
    * @param response
    * @return
    * @throws Exception
   */
   @RequestMapping("/delete")
   public void delete(String ids,HttpSession session, HttpServletResponse response) throws Exception{
       System.out.println(ids);
       ids=ids.replace("'",""); 
       /*
        * 多删除返回影响行数
       */
       Integer count = upmsStaffRoleService.delete(ids);
       if (count >= 1) {
           response.getWriter().print("1");
       }else{
           response.getWriter().print("0");
       }
   }
   /**
    * 条件查询员工+角色
    * @param upmsStaffRole 员工+角色实体类
    * @return 员工+角色实体类集合
   */
   @RequestMapping("/queryAll")
   @ResponseBody
   public List<UpmsStaffRole> queryAllByMution(UpmsStaffRole upmsStaffRole){
       List<UpmsStaffRole> list = upmsStaffRoleService.queryAllByMution(upmsStaffRole);
       return list;
   }
   /**
    * 根据id查员工+角色
    * @param id 员工+角色id
    * @return 员工+角色实体类
   */
   @RequestMapping("/queryById")
   @ResponseBody
   public UpmsStaffRole queryById(Long id){
       UpmsStaffRole upmsStaffRole = upmsStaffRoleService.queryById(id);
       return upmsStaffRole;
   }
   /**
    * 修改部门
    * @param upmsStaffRole 员工+角色实体类
    * @param session
    * @param response
    * @return
    * @throws Exception
   */
   @RequestMapping("/update")
   public void update(String pass,UpmsStaffRole upmsStaffRole,HttpSession session, HttpServletResponse response) throws Exception{
       /*
        * 修改返回影响行数
       */
       Integer count = upmsStaffRoleService.update(upmsStaffRole);
       if (count >= 1) {
    	   UpmsStaff param = upmsStaffService.queryById(upmsStaffRole.getStaffId());
    	   if (StringUtil.isNotEmpty(pass)) {
    		   pass = MD5.md5Encode(pass);
    		   if(!pass.equals(param.getPass())){
    			   param.setPass(pass);
    			   upmsStaffService.update(param);
    		   }
    	   }
           response.getWriter().print("1");
       }else{
           response.getWriter().print("0");
       }
   }
   
   
   
   /**
	 * 导出当前页数据
	 * 
	 * @param engineering
	 *            工程
	 * @param response
	 *            response
	 * @throws Exception
	 *             异常
	 */
	@RequestMapping("/doExport")
	public void doExport(UpmsStaffRole upmsStaffRole, HttpServletResponse response)
			throws Exception {
		List<UpmsStaffRole> upmsStaffRoles = upmsStaffRoleService
				.findPageByMution(upmsStaffRole);
		List<List<String>> lists = upmsStaffRoleZhuanList(upmsStaffRoles);
		ExcelUtils.export("用户当前数据", namess(), response, lists);
	}

	/**
	 * 导出所有数据
	 * 
	 * @param engineering
	 *            工程
	 * @param response
	 *            response
	 * @throws Exception
	 *             异常
	 */
	@RequestMapping("/doExportall")
	public void doExportall(UpmsStaffRole upmsStaffRole,
			HttpServletResponse response) throws Exception {
		// 未删除
		List<UpmsStaffRole> upmsStaffRoles = upmsStaffRoleService
				.queryAllByMution(upmsStaffRole);
		List<List<String>> lists = upmsStaffRoleZhuanList(upmsStaffRoles);
		ExcelUtils.export("用户所有数据", namess(), response, lists);
	}

	/**
	 * 导入
	 * 
	 * @param file
	 * @param request
	 * @param response
	 * @throws URISyntaxException
	 *             URISyntaxException异常
	 * @throws IOException
	 *             IO流异常
	 */
	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest request, HttpServletResponse response)
			throws URISyntaxException, IOException {

		String savePath = request.getSession().getServletContext().getRealPath(
				"/WEB-INF/" + file.getOriginalFilename());
		File newFile = new File(savePath);
		// 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
		file.transferTo(newFile);
		// 取文件后缀
		String subfix = savePath.lastIndexOf(".") == -1 ? "" : savePath
				.substring(savePath.lastIndexOf(".") + 1);

		List<List<String>> lists = new ArrayList<>();
		// 获取导入行数
		List<String> names = names();
		int num = names.size();
		String xls = "xls";
		String xlsx = "xlsx";
		if (xls.equals(subfix)) {
			lists = ExcelUtils.readXls(savePath, request, num);
		} else if (xlsx.equals(subfix)) {
			lists = ExcelUtils.readXlsx(savePath, request, num);
		} else {
			response.getWriter().print("0");
		}


		int flag = 1;
		for (int i = 0; i < lists.size(); i++) {
			List<String> list = new ArrayList<>();
			list = lists.get(i);

			UpmsStaffRole upmsStaffRole = new UpmsStaffRole();

			if (StringUtil.isNotEmpty(list.get(0))) {
				UpmsRole upmsRole = new UpmsRole();
				upmsRole.setName(list.get(0));
				List<UpmsRole> upmsRoles = upmsRoleService.queryAllByMution(upmsRole);
				if (upmsRoles.size() == 1) {
					upmsStaffRole.setRoleId(upmsRoles.get(0).getRoleId());
				} else {
					flag = 0;
					break;
				}
			} else {
				flag = 0;
				break;
			}
			
			if (StringUtil.isNotEmpty(list.get(1))) {
				UpmsStaff upmsStaff = new UpmsStaff();
				upmsStaff.setScode(list.get(1));;
				List<UpmsStaff> upmsStaffs = upmsStaffService.queryAllByMution(upmsStaff);
				if (upmsStaffs.size() == 1) {
					upmsStaffRole.setStaffId(upmsStaffs.get(0).getStaffId());
				} else {
					flag = 0;
					break;
				}
			} else {
				flag = 0;
				break;
			}

			int ff = addUpmsStaffRole(upmsStaffRole, list.get(2));
			upmsStaffRole = null;
			if (ff == 0) {
				flag = 0;
				break;
			}
		}
		response.getWriter().print(flag);
	}

	/**
	 * 导出模板的表头
	 * 
	 * @return list集合
	 */
	public List<String> names() {
		List<String> list = new ArrayList<>();
		list.add("角色名称");
		list.add("员工工号");
		list.add("密码");
		return list;
	}

	/**
	 * 导出数据表头
	 * 
	 * @return list集合
	 */
	public List<String> namess() {
		List<String> list = new ArrayList<>();
		list.add("名称");
		list.add("标题");
		list.add("工号");
		list.add("姓名");
		return list;
	}

	/**
	 * 根据导出数据表头把List<upmsStaffRole>转List<List<String>>
	 * 
	 * @param upmsStaffRole
	 *            员工
	 * @return
	 */
	public List<List<String>> upmsStaffRoleZhuanList(
			List<UpmsStaffRole> upmsStaffRoles) {
		List<List<String>> lists = new ArrayList<>();
		for (UpmsStaffRole upmsStaffRole : upmsStaffRoles) {
			List<String> list = new ArrayList<>();

			if(null != upmsStaffRole.getUpmsRole()){
				// 名称
				list.add(upmsStaffRole.getUpmsRole().getName());
				// 标题
				list.add(upmsStaffRole.getUpmsRole().getTitle());
			}else{
				list.add("");
				list.add("");
			}
			if(null != upmsStaffRole.getUpmsStaff()){
				// 工号
				list.add(upmsStaffRole.getUpmsStaff().getScode());
				//姓名
				list.add(upmsStaffRole.getUpmsStaff().getSname());
			}else{
				list.add("");
				list.add("");
			}
			lists.add(list);
			list = null;
		}
		return lists;
	}

	/**
	 * 导入数据是的添加方法（如果不满足添加条件，直接过滤）
	 * 
	 * @param upmsStaffRole
	 *            用户
	 * @param pass
	 *            密码
	 * @return 成功标识
	 */
	public int addUpmsStaffRole(UpmsStaffRole upmsStaffRole, String pass) {
		int flag = 0;
		UpmsStaff paramf = new UpmsStaff();
		paramf.setStaffId(upmsStaffRole.getStaffId());
		List<UpmsStaff> queryAllByMution = upmsStaffService.queryAllByMution(paramf);
		if(queryAllByMution.size()>0){
			// 添加工程
			// 添加
			Long id = upmsStaffRoleService.insert(upmsStaffRole);
			// 添加成功
			if (null != id && id >= 1) {
				UpmsStaff param = upmsStaffService.queryById(upmsStaffRole.getStaffId());
				if (StringUtil.isNotEmpty(pass)) {
					param.setPass(MD5.md5Encode(pass));
				}else{
					param.setPass(MD5.md5Encode("123"));
				}
				upmsStaffService.update(param);
				flag = 1;
			}
		}else{
			flag = 1;
		}
		return flag;
	}
}
